<template>
  <div class="course-manage">
    <button
      class="add-btn"
      style="float:left"
      type="primary"
      size="mini"
      @click="courseOperate('add')"
    >添加课程</button>
    <compTable
      ref="table"
      size="mini"
      :search-keys="['text','groupNames','tagNames']"
      :table-height="500"
      :stripe="false"
      :show-checkbox="false"
      :table-header="tableHeader"
      :table-data="tableData"
      :show-menu="false"
      :page-data="pageData"
    />
  </div>
</template>

<script>
import { getLearnGroupList, getLearnTagList, setLearnBookEnable, delLearnBook } from '@/api/learnCenter'
import { getLearnBookList } from '@/api/learnCenter'
let that
export default {
  name: 'CourseManage',
  data() {
    return {
      typeList: [],
      labelList: [],
      searchParams: {
        bookName: '',
        groupID: '',
        tagID: ''
      },
      tableHeader: [
        { prop: 'groupNames', label: '分组', width: 'auto', render(h, { row }) {
          return (
            <span>{row['groupNames'].join(',')}</span>
          )
        } },
        { prop: 'tagNames', label: '标签', width: 'auto', render(h, { row }) {
          return (
            <span>{row['tagNames'].join(',')}</span>
          )
        } },
        { prop: 'text', label: '课程名称', width: 'auto' },
        { prop: 'createName', label: '创建人', width: 'auto' },
        { prop: 'createTime', label: '创建时间', width: 140 },
        { prop: 'enable', label: '是否启用', width: 80, align: 'center', render(h, { row }) {
          let text = '禁用'
          let type = 'info'
          if (row.enable === '1') {
            text = '启用'
            type = ''
          }
          return (
            <el-button type={type} plain size='mini' nativeOnClick={ () => that.courseEnable(row)}>{text}</el-button>
          )
        } },
        { prop: 'title', label: '操作', width: 150, align: 'center', render(h, { row }) {
          return (
            <span>
              <el-button plain size='mini' nativeOnClick={() => that.courseOperate('edit', row)}>编辑</el-button>
              <el-button plain size='mini' nativeOnClick={() => that.courseOperate('del', row)}>删除</el-button>
            </span>
          )
        } }
      ],
      tableData: [],
      pageData: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  async created() {

  },
  async activated() {
    that = this
    await this.getTypeList() // 获取类型列表
    await this.getLabelList() // 获取标签
    this.getCourseList() // 获取课程列表
  },
  methods: {
    // 获取类型列表
    getTypeList() {
      return new Promise((res, rej) => {
        const vPar = new this.ParamArr()
        getLearnGroupList(vPar).then(vPar => {
          const nodes = []
          const table = new this.SQLTable(vPar.getTable('k_learn_group'))
          table.first()
          while (!table.eof()) {
            const node = {}
            node['id'] = table.getValueByName('ID')
            node['pid'] = table.getValueByName('PID')
            node['text'] = table.getValueByName('Name')
            node['iType'] = table.getValueByName('iType')
            nodes.push(node)
            table.next()
          }
          this.typeList = nodes
          res()
        })
      })
    },
    // 获取标签
    getLabelList() {
      return new Promise((res, rej) => {
        const vPar = new this.ParamArr()
        getLearnTagList(vPar).then(vPar => {
          const nodes = []
          const table = new this.SQLTable(vPar.getTable('k_learn_tag'))
          table.first()
          while (!table.eof()) {
            const node = {}
            node['id'] = table.getValueByName('ID')
            node['pid'] = table.getValueByName('PID')
            node['text'] = table.getValueByName('Name')
            node['iType'] = table.getValueByName('iType')
            nodes.push(node)
            table.next()
          }
          this.labelList = nodes
          res()
        })
      })
    },
    // 获取课程列表
    getCourseList() {
      const vPar = new this.ParamArr()
      vPar.setStr('BookName', this.searchParams.bookName)
      vPar.setStr('GroupID', this.searchParams.groupID)
      vPar.setStr('TagID', this.searchParams.tagID)
      getLearnBookList(vPar).then(vPar => {
        // console.log('data')
        // console.log(vPar)
        const nodes = []
        const table = new this.SQLTable(vPar.getTable('k_learn_book'))
        table.first()
        while (!table.eof()) {
          const node = {}
          node['id'] = table.getValueByName('ID')
          node['text'] = table.getValueByName('Name')
          node['remark'] = table.getValueByName('Remark')
          node['groupIDs'] = table.getValueByName('GroupIDs')
          node['tagIDs'] = table.getValueByName('TagIDs')
          node['createTime'] = table.getValueByName('CreateTime')
          node['createBy'] = table.getValueByName('CreateBy')
          node['modifyBy'] = table.getValueByName('ModifyBy')
          node['enable'] = table.getValueByName('Enable')
          node['createName'] = table.getValueByName('CreateName')
          node['modifyName'] = table.getValueByName('ModifyName')
          // 处理分类
          const groupNames = []
          const groupIDs = node['groupIDs'].split(',')
          const tagIDs = node['tagIDs'].split(',')
          this.typeList.forEach(it1 => {
            groupIDs.forEach(it2 => {
              if (it1.id === it2) {
                groupNames.push(it1.text)
              }
            })
          })
          // 处理标签
          const tagNames = []
          this.labelList.forEach(it1 => {
            tagIDs.forEach(it2 => {
              if (it1.id === it2) {
                tagNames.push(it1.text)
              }
            })
          })
          node['groupNames'] = groupNames
          node['tagNames'] = tagNames
          nodes.push(node)
          table.next()
        }
        this.tableData = nodes
      })
    },
    // 禁启用课程
    courseEnable(row) {
      const vPar = new this.ParamArr()
      vPar.setStr('ID', row.id)
      vPar.setInt('Enable', row.enable == 1 ? 0 : 1)
      setLearnBookEnable(vPar).then(vPar => {
        this.$set(row, 'enable', row.enable == 1 ? '0' : '1')
      })
    },
    courseOperate(type, row) {
      switch (type) {
        case 'add':
          this.$router.push({ name: 'CourseOperate', params: { id: 'new_' + this.Global.getGuid() }})
          break
        case 'edit':
          this.$router.push({ name: 'CourseOperate', params: { id: row.id }})
          break
        case 'del':
          this.$comfirmDialog({
            message: `是否删除"${row.text}"?`,
            confirm: () => {
              const vPar = new this.ParamArr()
              vPar.setStr('ID', row.id)
              delLearnBook(vPar).then(vPar => {
                this.tableData = this.tableData.filter(item => item.id !== row.id)
              }).catch(err => {
                if (err.sError === '课程已经有学员参加，是否确认要删除？') {
                  const { vPar } = err
                  const adminUser = vPar.getBool('AdminUser') // 是否是管理员
                  this.$comfirmDialog({
                    message: err.sError,
                    confirm: () => {
                      const vPar = new this.ParamArr()
                      vPar.setStr('ID', row.id)
                      vPar.setBool('ForceDelete', adminUser)
                      delLearnBook(vPar).then(vPar => {
                        this.tableData = this.tableData.filter(item => item.id !== row.id)
                      })
                    }
                  })
                } else {
                  this.$message.error(err.sError)
                }
              })
            }
          })
          break
      }
    }
  }
}
</script>

<style scoped lang="scss">
.course-manage {
  width: 100%;
  padding: 10px;
}
.top-table-tool {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .left-tool {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.add-btn {
  width: 96px;
	height: 30px;
	background-color: $primaryColor;
	font-size: 14px;
	color: #ffffff;
  outline: none;
  border: none;
  cursor: pointer;
}
</style>
